package com.github.ghsea.framework.job.common;

import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

public abstract class AbstractEndpointLocator implements EndpointLocator {

	private AtomicLong idx = new AtomicLong(0);

	public Endpoint select() {
		long index = idx.getAndIncrement();
		if (index >= Long.MAX_VALUE) {
			synchronized (idx) {
				if (index >= Long.MAX_VALUE) {
					idx.set(0L);
				}
			}
		}

		List<Endpoint> allEndpoints = listAll();
		if (allEndpoints.size() == 0) {
			return null;
		}

		return allEndpoints.get((int) index % allEndpoints.size());
	}

	protected abstract List<Endpoint> listAll();
}
